/**
 * Copyright 1999-2014 dangdang.com.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyer.lxp.common.framework.exception;

import com.qyer.lxp.common.framework.contants.ClientErrorMessageEnum;
import org.apache.log4j.Logger;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;

/**
 * @author jiangping
 */
public class CustomExceptionMapper implements ExceptionMapper<Exception> {

    private static final Logger logger = Logger
            .getLogger(CustomExceptionMapper.class);

    /**
     * Map an exception to a {@link Response}. Returning
     * {@code null} results in a {@link Response.Status#NO_CONTENT}
     * response. Throwing a runtime exception results in a
     * {@link Response.Status#INTERNAL_SERVER_ERROR} response.
     *
     * @param exception the exception to map to a response.
     * @return a response mapped from the supplied exception.
     */
    @Override
    public Response toResponse(Exception exception) {
        String response;
        int code;
        if(exception instanceof QyerClientException){
            QyerClientException qyerClientException=(QyerClientException)exception;
            response="{\"namespace\":\"error\",\"status\":\""+qyerClientException.getStatusCode()+"\",\"msg\":\""+qyerClientException.getStatusMessage()+"\",\"data\":{}}";
            code=ClientErrorMessageEnum.CLIENT_RESPONSE_200.getCode();
            return Response.status(code).entity(response).type(MediaType.APPLICATION_JSON).build();
        }else{
            response="{\"namespace\":\"error\",\"status\":\"100\",\"msg\":\"Unknow Exception\",\"data\":{}}";
            logger.error(exception.getMessage(), exception);
            code= ClientErrorMessageEnum.CLIENT_RESPONSE_100.getCode();
        }
        return Response.serverError().entity(response).type(MediaType.APPLICATION_JSON).build();
    }
}
